package dz.common;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;

public class DBHelper {
	static Map<String,Connection> consmap = new HashMap<String,Connection>(); 

	public static Connection getConnection(String dbfilepath){
		Connection con = consmap.get(dbfilepath);
		if(con == null){
			try {
				Class.forName("org.sqlite.JDBC");
				con = DriverManager.getConnection("jdbc:sqlite://"+ dbfilepath);
				consmap.put(dbfilepath, con);
				return con;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return con;
	}
	


	public static void createTable(Statement stat, String table) {
		try {
				stat.executeUpdate("create table if not exists " + table +"(" +
						"id integer(20)," +//1
						"createtimestamp char(20)," +
						"updatetimestamp char(20)" +						
						");");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void execSQL(Connection conn, String sql) {
		Statement stat = null;
		try {
			stat = conn.createStatement();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		try {
			stat.executeUpdate(sql);
			stat.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static boolean hasColumn(Connection conn,String table, String column){
		boolean result = false;
		String sql = "select * from sqlite_master where tbl_name='"+table+"';";
			try {
				Statement stat = conn.createStatement();
				ResultSet rs;
				rs = stat.executeQuery(sql);
				while (rs.next()) {
					if(rs.getString("sql").contains(column)){
						result =  true;
					}
				}
				rs.close();
				stat.close();
			} catch (SQLException e) {
				e.printStackTrace();
			} 
			return result;
	}
	
	public static void addColumn(Connection conn, String table, String column, String datatype) {
		String sql = "ALTER TABLE '"+table+"' ADD COLUMN '" + column + "' " + datatype;
		try {
			Statement stat = conn.createStatement();
				stat.executeUpdate(sql);
				stat.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


}
